#!/usr/bin/evn python
# -*- coding: utf-8 -*-


import grpc
from example.stubs import hello_pb2
from example.stubs import hello_pb2_grpc

 # 连接consul服务，作为dns服务器



from dns import resolver
from dns.exception import DNSException

# 创建一个consul dns查询的 resolver
consul_resolver = resolver.Resolver()
consul_resolver.port = 8600
consul_resolver.nameservers = ['127.0.0.1']


def get_ip_port(server_name):
    '''查询出可用的一个ip，和端口'''
    try:
        dnsanswer = consul_resolver.resolve(f'{server_name}.service.consul', "A")
        dnsanswer_srv = consul_resolver.resolve(f"{server_name}.service.consul", "SRV")
    except DNSException:
        return None, None
    return dnsanswer[0].address, dnsanswer_srv[0].port

from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel




def run(i):

    compression = grpc.Compression.Gzip
    # 添加客户端的请求拦截器
    # 单纯的子节点上传了，父节点没有上传
    with grpc.insecure_channel(target=f'127.0.0.1:45564',compression=compression) as channel:
        # 通过通道服务一个服务intercept_channel
        # interceptor_channel = grpc.intercept_channel(channel,*middlewares)
        stub = hello_pb2_grpc.GreeterStub(channel)
        # 生成请求我们的服务的函数的时候，需要传递的参数体，它放在hello_pb2里面-请求体为：hello_pb2.HelloRequest对象
        try:
            # 藕信息里面不能包含有：--------------------------不然会TypeError: not all arguments converted during string formatting
            reest_header = (
                ('mesasge', 'mes'+str(i)),
                ('error', 'as')
            )
            response, callbask = stub.SayHelloAgain.with_call(request=hello_pb2.HelloRequest(name='欢迎下次光临'+str(i)),
                                                              # 设置请求的超时处理
                                                              timeout=5,
                                                              # 设置请求的头的信息
                                                              metadata=reest_header,
                                                              )
            print("SayHelloAgain函数调用结果的返回: " + response.message)
            print("SayHelloAgain函数调用结果的返回---响应报文头信息: ", callbask.trailing_metadata())
        except grpc._channel._InactiveRpcError as e:
            print(e.code())
            print(e.details())
        finally:
            # 关闭追踪
            pass
            # time.sleep(2)
            # time.sleep(3)


if __name__ == '__main__':
    # 创建新线程
    import threading

    threads = []

    for x in range(3):
        t = threading.Thread(target=run, args=(x,))
        # 把多线程的实例追加入列表，要启动几个线程就追加几个实例
        threads.append(t)
    for thr in threads:
        # 把列表中的实例遍历出来后，调用start()方法以线程启动运行
        thr.start()
        thr.join()
    # for thr in threads:
    #     """
    #     isAlive()方法可以返回True或False，用来判断是否还有没有运行结束
    #     的线程。如果有的话就让主线程等待线程结束之后最后再结束。
    #     """
    #     if thr.isAlive():
    #         thr.join()
